package ci.web.codec;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.ssl.SslHandler;

/**
 * 解码第一个数据包,如果发现不是https协议，则重定向到https
 * @author zhh
 */
class HttpToHttpsDecoder extends ByteToMessageDecoder {

	private ChannelHandler handler;
	public HttpToHttpsDecoder(ChannelHandler handler) {
		this.handler = handler;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		if(in.readableBytes()>5){
			if(SslHandler.isEncrypted(in)==false){
				ctx.pipeline().remove(SslHandler.class);
				ctx.pipeline().remove(handler);
				ctx.pipeline().addLast(HttpToHttpsHandler.instance);
			}
			ctx.pipeline().remove(this);
		}
	}

}
